<?php

namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Biz\tools\ShopArea;
use Doraemon\cache\Designer\DesignerViolation as cDesignerViolation;
use Doraemon\model\AdmSaleBind\AdmSaleBind;
use Doraemon\model\AdmSaleBind\AdmSaleBindLog;
use Doraemon\model\Article;
use Doraemon\model\BlackList;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerAuditLog;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerAuthExtend;
use Doraemon\model\DesignerAuthPhotos;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\DesignerOrder;
use Doraemon\model\DesignerPayService;
use Doraemon\model\DesignerTeam;
use Doraemon\model\KaDesigner;
use Doraemon\model\Member;
use Doraemon\model\MemberHistoryNick;
use Doraemon\service\BusinessUser\EncryptPhone;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use hhz\constant\basic\UserExtendPhoneScene;
use Doraemon\service\Designer\DesignerViolationRecord as sDesignerViolationRecord;
use Doraemon\model\Designer\DesignerViolationRecord;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\Photos;
use Doraemon\service\WechatAlert;
use Doraemon\tools\BackendTool;
use Doraemon\tools\ImgUrl;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\model\Designer\DesignerOpLog;
use Doraemon\service\Milvus\BusinessJudgeArticle as sBusinessJudgeArticle;

class DesignerAuthController extends Controller
{
	const PAGE_SIZE = 20;

	const PAY_STATUS = [
		0 => '未支付',
		1 => '已支付'
	];

	const STATUS_AUTH = [
		'' => '全部',
		1 => '未认证',
		5 => '已认证',
		6 => '取消认证',
		7 => '认证过期'
	];

	const STATUS_AUDIT = [
		'' => '全部',
		0 => '待补充',
		1 => '审核中',
		2 => '未通过审核',
		3 => '通过审核'
	];

	const IS_TEST = [
		0 => '否',
		1 => '是'
	];

	const DESIGNER_TYPE_OPTIONS = [
		'' => '全部',
		DesignerAuth::DESIGNER_TYPE_SINGLE => '独立个人',
		DesignerAuth::DESIGNER_TYPE_COMPANY => '设计机构/工作室',
		DesignerAuth::DESIGNER_TYPE_COMPANY_EMPLOYEE => '在职个人',
		DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS => '机构子账号'
	];

	// 服务类别
	const SERVICE_TYPE = [
		1 => '付费认证',
		2 => '青年计划',
		3 => '大V白名单',
		4 => '免费体验一个月',
		5 => '线下付款年费',
		6 => '线下付款季费',
		7 => '免费绑定'
	];

	// 服务数据状态
	const SERVICE_STATUS_TEXT = [
		1 => '正常',
		2 => '冻结',
		3 => '终止',
	];

	// 所学专业
	const MAJOR = [
		1 => '环境艺术设计/室内设计',
		2 => '工业设计/产品设计',
		3 => '平面设计',
		4 => '美术类：雕塑艺术、油画、美术学等',
		5 => '建筑类：建筑设计、建筑装饰、建筑装饰工程技术等',
		6 => '其他',
	];

	// 是否在设计公司或装饰公司工作过
	const IS_WORK_DESIGN = [
		0 => '否',
		1 => '是',
	];

	// 团队规模
	const TEAM_SIZE = [
		1 => '1-3人',
		2 => '4-6人',
		3 => '7-10人',
		4 => '11-50人',
		5 => '51-100人',
		6 => '100人以上',
	];

	// 工作岗位
	const JOB = [
		0 => '非设计师',
		1 => '设计师',
	];

	// 最高学历
	const EDUCATION = [
		1 => '大专及以下',
		2 => '本科',
		3 => '硕士',
		4 => '博士及以上',
	];

	// 你是从哪儿知道好好住APP，并下载使用的？
	const WHERE_KNOW = [
		1 => '好好住微博、微信公众号',
		2 => '营造家微博、微信公众号',
		3 => '营造家设计师大赛',
		4 => '好好住官方联系',
		5 => '朋友推荐',
		6 => '客户推荐',
		7 => '同行/同事推荐',
		8 => 'APP store/安卓应用市场推荐',
		9 => '知乎',
		10 => '其他',
	];

	const SERVICE_SCOPE = [
		1 => '只做纯设计',
		2 => '只做设计师施工一体',
		3 => '以上都接'
	];

	// 有长期合作或者自己的施工队吗
	const IS_CREW = [
		0 => '无',
		1 => '有',
	];

	// 认证图片url可访问的有效时间30分钟
	const AUTH_PIC_EXPIRE_TIME = 1800;

	// 擅长的风格
	const GOOD_AT_STYLE =  [
		1 => '北欧',
		2 => '美式',
		3 => '日式',
		4 => '中式/新中式',
		5 => '轻奢',
		6 => '法式',
		7 => '欧式',
		8 => '现代',
		9 => '极简',
		10 => '混搭',
		11 => '工业风',
		12 => 'Vintage复古',
		13 => '东南亚',
		14 => '民族风',
		15 => '其他',
	];

	// 擅长的设计方向
	const GOOD_AT_DIRECTION = [
		1 => '小户型（≤60㎡）',
		2 => '大户型（≥150㎡）',
		3 => '别墅',
		4 => 'LOFT / 复式 / 跃层',
		5 => '老房二手房改造',
		6 => '局部改造',
		7 => '精装房改造',
		8 => '软装设计',
		9 => '色彩搭配',
		10 => '空间规划',
		11 => '收纳系统',
		12 => '亲子空间',
		13 => '其他',
	];

	// 用户未上传时默认显示的照片
	const DEFAULT_PIC = 'http://img.hhz1.cn/Op-imageShow/5472d20gy0gy0OI00qwa4rb?iv=1';

	// 每年做多家装项目
	const PRIVATE_JOB = [
		1 => '1-5',
		2 => '6-10',
		3 => '11-15',
		4 => '16-20',
		5 => '20+',
	];

	const SALE_LIST = [
		'renyuanxia',
		'cuihaijun',
		'lianghongchao',
		'marubin',
		'tianshu',
	];

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function index(Request $request, Content $content, $tab_id = 1)
	{
		$tab = new Tab();
		$tab->addLink('案例/资料审核', '/admin/DesignerAuth/1', $tab_id == 1);
		$tab->addLink('待开通认证', '/admin/DesignerAuth/2', $tab_id == 2);
		$tab->addLink('审核操作记录', '/admin/DesignerAuth/3', $tab_id == 3);

		if ($tab_id == 1) {
			$row = $this->listCase($request);
		} elseif ($tab_id == 2) {
			$row = $this->wait($request);
		} elseif ($tab_id == 3) {
			$row = $this->opRecord($request);
		}

		$header = '设计师入驻审核';
		return $content
			->header($header)
			->breadcrumb(['text' => $header])
			->body($tab)
			->row($row);
	}

	public function wait(Request $request)
	{
		$params = $request->all();
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [
			'auth_status[!]' => DesignerAuth::STATUS_AUTH_COMPLETE,
			'is_pay' => DesignerAuth::HAVE_PAID,
			'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_PASS,
			'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_PASS,
		];

		$condition['ORDER'] = ['id' => 'DESC'];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = DesignerAuth::select('*', $condition);

		$total = 0;
		if (!empty($lists)) {
			unset($condition['ORDER']);
			unset($condition['LIMIT']);
			$total = DesignerAuth::count($condition);
//			$user_ids = array_column($lists, 'uid');
//			$member_info = Member::getUsers($user_ids);
			foreach ($lists as &$item) {
//				$item['nick'] = empty($member_info[$item['uid']]['nick']) ?
//					'' : $member_info[$item['uid']]['nick'];
				$item['designer_type'] = self::DESIGNER_TYPE_OPTIONS[$item['designer_type']];
				$item['house_article_audit_status'] = self::STATUS_AUDIT[$item['house_article_audit_status']];
				$item['identity_info_audit_status'] = self::STATUS_AUDIT[$item['identity_info_audit_status']];
				$item['is_pay'] = self::PAY_STATUS[$item['is_pay']];
				$item['is_test'] = self::IS_TEST[$item['is_test']];
				$item['auth_status'] = DesignerAuth::AUTH_STATUS_DESC[$item['auth_status']];
				$item['auth_time'] = empty($item['auth_time']) ? '-' : date('Y-m-d H:i:s', $item['auth_time']);
				$item['expire_time'] = empty($item['expire_time']) ? '-' : date('Y-m-d H:i:s', $item['expire_time']);
				$item['operate_time'] = empty($item['operate_time']) ? '-' : date('Y-m-d H:i:s', $item['operate_time']);
                //历史昵称
                $item['history_nick'] = self::getHistoryNick($item['uid']);
                // 违规记录数量展示
                $item['violation_list']['uid'] = DesignerViolationRecord::count(['designer_uid' => $item['uid'], 'data_status' => DesignerViolationRecord::STATUS_NORMAL]);
                $identityNumber = $item['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY ? $item['business_license_number'] : $item['id_card_number'];
                $item['violation_list']['identity_number'] = $identityNumber ? DesignerViolationRecord::count(['identity_number' => $identityNumber, 'data_status' => DesignerViolationRecord::STATUS_NORMAL]) : 0;
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
				$grid->disableFilter();

				$grid->column('uid', 'uid')->width(100)->copyable();
				$grid->column('nick', '昵称')->width(150)->copyable();
				$grid->column('history_nick', '历史昵称')->width(100);
				$grid->column('designer_type', '设计师类别')->width(100);
                $grid->column('violation_list', '违规记录')->display(function () {
                    if ($this->violation_list['uid']) {
                        $violationListTxt[] = "UID：<a href='/admin/Violation/designer?designer_uid={$this->uid}'>".$this->violation_list['uid']."</a>";
                    }
                    if ($this->designer_type == DesignerAuth::DESIGNER_TYPE_COMPANY) {
                        $identityKey = 'business_license_number';
                    } else {
                        $identityKey = 'id_card_number';
                    }
                    if ($this->violation_list['identity_number']) {
                        $violationListTxt[] = "证件号：<a href='/admin/Violation/designer?identity_number={$this->$identityKey}'>".$this->violation_list['identity_number']."</a>";
                    }
                    return !empty($violationListTxt) ? implode('<br>', $violationListTxt) : '';
                })->width(200);
				$grid->column('create_time', '首次提交申请时间')->width(140);
				$grid->column('house_article_audit_status', '案例审核状态')->display(function ($title, Grid\Column $column) {
					return $column->label('success');
				})->width(100);
				$grid->column('update_time', '最近一次修改资料时间')->width(140);
				$grid->column('identity_info_audit_status', '资料审核状态')->display(function ($title, Grid\Column $column) {
					return $column->label('success');
				})->width(100);
				$grid->column('is_pay', '支付状态')->width(100);
				$grid->column('auth_time', '认证时间')->width(100);
				$grid->column('expire_time', '到期时间')->width(100);
				$grid->column('auth_status', '认证状态')->width(100);
				$grid->column('remark', '补充说明')->width(100);
				$grid->column('remark2', '备注')->width(100)->editable();
				$grid->column('is_test', '测试号')->width(60);
				$grid->column('admin_id', '处理人')->display(function () {
					if (!$this->admin_id) {
						return '-';
					} else {
						return Admin::user()->find($this->admin_id)->name;
					}
				})->width(100);
				$grid->column('operate_time', '处理时间')->width(140);

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					$actions->disableView();
					$actions->disableEdit();
					$actions->append("<a href=\"detail/" .
						$actions->row->uid . "\" class=\"btn btn-primary\" style='margin-bottom: 5px'><i class=\"fa fa-eye\">&nbsp;查看案例/资料</i></a>");
                    $actions->append(BackendTool::addConfirmLayerBtnWithHref(
                        '是否现在就给该账号开通认证？',
                        '开通认证',
                        '/admin/DesignerAuth/services/'.$actions->row->uid,
                        'fa fa-envira',
                        'margin-bottom:5px'
                    ));
				});
			}
		);
		return $gridList->render();
	}

	public function listCase(Request $request)
	{
		Admin::script($this->cancelAuthPop());

		$params = $request->all();
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [];
		if (!empty($params['keyword'])) {
			if (is_numeric($params['keyword'])) {
				$condition['uid'] = $params['keyword'];
			} else {
//				$uid = User::getUidByNick($params['keyword']);
				$condition['nick[~]'] = $params['keyword'];
			}
		}

		if ($params['house_article_audit_status'] != '') {
			$condition['house_article_audit_status'] = $params['house_article_audit_status'];
		}

		if ($params['identity_info_audit_status'] != '') {
			$condition['identity_info_audit_status'] = $params['identity_info_audit_status'];
		}

		if (!empty($params['auth_status'])) {
			$condition['auth_status'] = $params['auth_status'];
		}

		if (!empty($params['designer_type'])) {
			$condition['designer_type'] = $params['designer_type'];
		}

		if ($params['is_test'] != '') {
			$condition['is_test'] = $params['is_test'];
		}

		if (!empty($params['auth_time']['start'])) {
			$condition['auth_time[>=]'] = strtotime($params['auth_time']['start']);
		}

		if (!empty($params['auth_time']['end'])) {
			$condition['auth_time[<=]'] = strtotime($params['auth_time']['end']. " 23:59:59");
		}

		if (!empty($params['update_time']['start'])) {
			$condition['update_time[>=]'] = $params['update_time']['start']. ' 00:00:00';
		}

		if (!empty($params['update_time']['end'])) {
			$condition['update_time[<=]'] = $params['update_time']['end']. " 23:59:59";
		}

		if (!empty($params['create_time']['start'])) {
			$condition['create_time[>=]'] = $params['create_time']['start']. ' 00:00:00';
		}

		if (!empty($params['create_time']['end'])) {
			$condition['create_time[<=]'] = $params['create_time']['end']. " 23:59:59";
		}

		if (!empty($params['expire_time']['start'])) {
			$condition['expire_time[>=]'] = strtotime($params['expire_time']['start']);
		}

		if (!empty($params['expire_time']['end'])) {
			$condition['expire_time[<=]'] = strtotime($params['expire_time']['end']. " 23:59:59");
		}

		$condition['ORDER'] = ['update_time' => 'DESC'];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = DesignerAuth::select('*', $condition);

		$total = 0;
		if (!empty($lists)) {
			unset($condition['ORDER'], $condition['LIMIT']);
			$total = DesignerAuth::count($condition);
			$user_ids = array_column($lists, 'uid');
//			$member_info = Member::getUsers($user_ids);

			$sale_bind_info = AdmSaleBind::select('*', [
				'uid' => $user_ids,
				'data_status' => AdmSaleBind::STATUS_NORMAL,
			]);
			$map_sale = array_column($sale_bind_info, 'admin_name', 'uid');

			foreach ($lists as &$item) {
//				$item['nick'] = empty($member_info[$item['uid']]['nick']) ?
//					'' : $member_info[$item['uid']]['nick'];
				$item['sale_bind'] = empty($map_sale[$item['uid']]) ? '' : $map_sale[$item['uid']];
				$item['designer_type'] = self::DESIGNER_TYPE_OPTIONS[$item['designer_type']];
				$item['is_pay'] = self::PAY_STATUS[$item['is_pay']];
				$item['is_test'] = self::IS_TEST[$item['is_test']];
				$item['auth_status_text'] = DesignerAuth::AUTH_STATUS_DESC[$item['auth_status']];
				$item['house_article_audit_status'] = self::STATUS_AUDIT[$item['house_article_audit_status']];
				$item['identity_info_audit_status'] = self::STATUS_AUDIT[$item['identity_info_audit_status']];
				$item['auth_time'] = empty($item['auth_time']) ? '-' : date('Y-m-d H:i:s', $item['auth_time']);
				$item['expire_time'] = empty($item['expire_time']) ? '-' : date('Y-m-d H:i:s', $item['expire_time']);
				$item['operate_time'] = empty($item['operate_time']) ? '-' : date('Y-m-d H:i:s', $item['operate_time']);
				//历史昵称
                $item['history_nick'] = self::getHistoryNick($item['uid']);
                // 违规记录数量展示
                $item['violation_list']['uid'] = DesignerViolationRecord::count(['designer_uid' => $item['uid']]);
                $identityNumber = $item['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY ? $item['business_license_number'] : $item['id_card_number'];
                $item['violation_list']['identity_number'] = $identityNumber ? DesignerViolationRecord::count(['identity_number' => $identityNumber]) : 0;
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);

		unset($condition['LIMIT']);
		$search_params = http_build_query($condition);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel, $search_params) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();

				// 添加导出按钮
				$grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
					$url = url('/admin/DesignerAuth/export/auth_data?'. $search_params);
					$button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出认证表</span></a>
                    </div>';
					$tool->append($button);
				});

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('keyword', '按昵称或uid检索')->placeholder('请输入uid或者昵称');
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('house_article_audit_status', '案例审核状态')->select(self::STATUS_AUDIT);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('identity_info_audit_status', '资料审核状态')->select(self::STATUS_AUDIT);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('auth_status', '认证状态')->select(self::STATUS_AUTH);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('designer_type', '设计师类别')->select(self::DESIGNER_TYPE_OPTIONS);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('is_test', '是否测试号')->select(self::IS_TEST);
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('auth_time', '认证日期')->date();
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('expire_time', '到期时间')->date();
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('update_time', '提交/更新资料时间')->date();
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('create_time', '首次提交申请日期')->date();
					});
					$filter->expand();
				});

				$grid->column('uid', 'uid')->width(100)->copyable();
				$grid->column('nick', '昵称')->width(150)->display(function () {
					if (empty($this->sale_bind)) {
						return $this->nick;
					} else {
						return $this->nick ."<br><b style='color: #0088cc'>对接销售(".$this->sale_bind . ")</b>";
					}
				});
				$grid->column('history_nick', '历史昵称')->width(100);
				$grid->column('designer_type', '设计师类别')->width(100);
                $grid->column('violation_list', '违规记录')->display(function () {
                    if ($this->violation_list['uid']) {
                        $violationListTxt[] = "UID：<a href='/admin/Violation/designer?designer_uid={$this->uid}'>".$this->violation_list['uid']."</a>";
                    }
                    if ($this->designer_type == DesignerAuth::DESIGNER_TYPE_COMPANY) {
                        $identityKey = 'business_license_number';
                    } else {
                        $identityKey = 'id_card_number';
                    }
                    if ($this->violation_list['identity_number']) {
                        $violationListTxt[] = "证件号：<a href='/admin/Violation/designer?identity_number={$this->$identityKey}'>".$this->violation_list['identity_number']."</a>";
                    }
                    return !empty($violationListTxt) ? implode('<br>', $violationListTxt) : '';
                })->width(200);
				$grid->column('create_time', '首次提交申请时间')->width(140);
				$grid->column('house_article_audit_status', '案例审核状态')->display(function ($title, Grid\Column $column) {
					if ($this->house_article_audit_status == '通过审核') {
						return $column->label('success');
					} else if ($this->house_article_audit_status == '待补充') {
						return $column->label('primary');
					} else if ($this->house_article_audit_status == '未通过审核') {
						return $column->label('danger');
					} else if ($this->house_article_audit_status == '审核中') {
						return $column->label('warning');
					} else {
						return '';
					}
				})->width(100);
				$grid->column('update_time', '更新资料时间')->width(140);
				$grid->column('identity_info_audit_status', '资料审核状态')->display(function ($title, Grid\Column $column) {
					if ($this->identity_info_audit_status == '通过审核') {
						return $column->label('success');
					} else if ($this->identity_info_audit_status == '待补充') {
						return $column->label('primary');
					} else if ($this->identity_info_audit_status == '未通过审核') {
						return $column->label('danger');
					} else if ($this->identity_info_audit_status == '审核中') {
						return $column->label('warning');
					} else {
						return '';
					}
				})->width(100);

				$grid->column('is_pay', '支付状态')->width(100);
				$grid->column('auth_time', '认证时间')->width(100);
				$grid->column('expire_time', '到期时间')->display(function() {
				    $expireTimeTxt = $this->expire_time;
				    if (cDesignerViolation::isInTagPool(sDesignerViolationRecord::getViolationCacheTag(sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW), $this->uid)) {
                        $expireTimeTxt .= "<br><span style='color:red'>(".sDesignerViolationRecord::PUNISH_TYPE_TXT_LIST[sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW].")</span>";
                    }
				    return $expireTimeTxt;
                })->width(100);
				$grid->column('auth_status_text', '认证状态')->width(100);
				$grid->column('remark', '补充说明')->width(100);
				$grid->column('remark2', '备注')->width(100)->editable();
				$grid->column('is_test', '测试号')->width(60);
				$grid->column('admin_id', '处理人')->display(function () {
					if (!$this->admin_id) {
						return '-';
					} else {
						return Admin::user()->find($this->admin_id)->name;
					}
				})->width(100);
				$grid->column('operate_time', '处理时间')->width(140);

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					$actions->disableView();
					$actions->disableEdit();
					$actions->append("<a href=\"detail/" .
						$actions->row->uid . "\" class=\"btn btn-primary\" style='margin-bottom: 5px'><i class=\"fa fa-legal\">&nbsp;审核案例/资料</i></a>");
					if (empty($actions->row->sale_bind)) {
						$actions->append("<a href=\"sale_bind/bind/" .
							$actions->row->uid . "\" class=\"btn btn-primary\" style='margin-bottom: 5px'><i class=\"fa fa-check\">&nbsp;销售认领客户</i></a>");
					} else {
						$actions->append("<a href=\"sale_bind/unbind/" .
							$actions->row->uid . "\" class=\"btn btn-danger\" style='margin-bottom: 5px'><i class=\"fa fa-close\">&nbsp;销售取消认领客户</i></a>");
					}
					if ($actions->row->auth_status == DesignerAuth::STATUS_AUTH_COMPLETE) {
//						$actions->append("<a onclick=\"return confirm('请确认是否取消认证')\" href=\"cancel_auth/" .
//							$actions->row->uid . "\" class=\"btn btn-danger\"><i class=\"fa fa-close\">&nbsp;取消认证</i></a>");
						$actions->append('<a class="btn btn-danger fa fa-close cancel-auth" href="javascript:;" data-uid="'.$actions->row->uid.'" data-nick="'.$actions->row->nick.'">&nbsp;取消认证</a>');
					}
				});
			}
		);
		return $gridList->render();
	}

	/**
	 * 认证资料审核详情页
	 * @param Request $request
	 * @param Content $content
	 * @param $uid
	 * @return Content
	 */
	public function detail(Request $request, Content $content, $uid)
	{
		$auth_info = DesignerAuth::get('*', [
			'uid' => $uid
		]);
		$auth_extend_info = DesignerAuthExtend::get('*', [
			'uid' => $uid
		]);
		$data = $auth_info;
		if (!empty($auth_extend_info)) {
			unset($auth_extend_info['create_time'], $auth_extend_info['update_time']);
			$data = array_merge($auth_info, $auth_extend_info);
		}

		// 用户基础信息
		$user_info = Member::getUser($uid);

		$tab = new Tab();
		$tab->add('认证信息', $this->basicPage($data, $user_info));

		$button = '';
		if (in_array($auth_info['house_article_audit_status'], [DesignerAuth::STATUS_AUDIT_WAIT, DesignerAuth::STATUS_AUDIT_FAIL])) {
			if (!in_array(Admin::user()->username, self::SALE_LIST)) {
				$button .= '
				<a href="/admin/DesignerAuth/case_pass/' . $uid . '" class="btn btn-primary" onclick="return confirm(\'确认案例审核通过吗？\');">案例审核通过</a>';
			}

			$button .= '
			<a href="javascript:layer.open({
                        type: 2,
                        title: \'案例审核不通过\',
                        maxmin: true,
                        area: [\'800px\', \'500px\'],
                        content: \'/admin/DesignerAuth/case_reject/' . $uid . '\'
                        });" class="btn btn-primary">案例审核不通过</a>';
		}

		if ($auth_info['identity_info_audit_status'] == DesignerAuth::STATUS_AUDIT_WAIT) {
			$button .= '
			<a href="/admin/DesignerAuth/info_pass/' . $uid . '" class="btn btn-primary" onclick="return confirm(\'确认资料审核通过吗？\');">资料审核通过</a>
        	<a href="javascript:layer.open({
                        type: 2,
                        title: \'资料审核不通过\',
                        maxmin: true,
                        area: [\'800px\', \'500px\'],
                        content: \'/admin/DesignerAuth/info_reject/' . $uid . '\'
                        });" class="btn btn-primary">资料审核不通过</a>
			';
		}
		$button .= '
	    <a href="javascript:layer.open({
                type: 2,
                title: \'填写备注\',
                maxmin: true,
                area: [\'800px\', \'500px\'],
                content: \'/admin/DesignerAuth/remark/' . $uid . '\'
                });" class="btn btn-primary">填写备注</a>';

//		if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE) {
//			$button .= '
//            <a href="javascript:layer.open({
//                        type: 2,
//                        title: \'取消设计师认证\',
//                        maxmin: true,
//                        area: [\'800px\', \'500px\'],
//                        content: \'/admin/DesignerAuth/cancel_auth/' . $uid . '\'
//                        });" class="btn btn-danger">取消认证</a>';
//		}

		if ($auth_info['house_article_audit_status'] == DesignerAuth::STATUS_AUDIT_PASS &&
			$auth_info['identity_info_audit_status'] == DesignerAuth::STATUS_AUDIT_PASS &&
			$auth_info['is_pay'] == DesignerAuth::HAVE_PAID && $auth_info['auth_status'] != DesignerAuth::STATUS_AUTH_COMPLETE) {
            $button .= BackendTool::addConfirmLayerBtnWithHref(
                '是否现在就给该账号开通认证？',
                '开通认证',
                '/admin/DesignerAuth/services/'.$uid,
                '',
                'margin-left:2px'
            );
		}

		$op = '<div style="text-align: right;margin-bottom: 10px;">'. $button .'</div>';
		return $content
			->header('入驻资料信息详情')
			->breadcrumb([
				'text' => '案例/资料审核列表',
				'url' => route('list', ['tab' => 1])
			], [
				'text' => '入驻信息详情'
			])
			->row($op)
			->body($tab);

	}

	public function edit(Request $request, Content $content, $id = 0)
	{
		$params = $request->all();
		$tab = new Tab();
		$tab->add('基本信息', self::editAction($params, $id));

		$header = '入驻资料详情';
		return $content->header($header)
			->description(' ')
			->breadcrumb([
				'text' => '入驻资料列表',
				'url' => route('index.list')
			], ['text' => $header])->row($tab);
	}

	public function editAction($request, $id = 0)
	{
		$data = DesignerAuth::get('*', ['id' => $id]);
		$data['nick'] = Member::getNickByUid($data['uid']);

		$form = new Form($data);
		$form->hidden('id');
		$form->display('uid', '用户UID')->setWidth(4, 2)->readOnly();
		$form->display('nick', '昵称')->setWidth(4, 2)->readOnly();

		$form->action('/admin/Designer/team/save');

		return $form->render();
	}

	public function editSubmit(Request $request)
	{
		$request = $request->all();

		if (empty(trim($request['remark']))) {
			$error = new MessageBag([
				'title' => '必须填写备注'
			]);

			return back()->withInput()->with(compact('error'));
		}

		$data = [
			'org_uid' => $request['org_uid'],
			'member_uid' => $request['member_uid'],
			'position' => $request['position'],
			'status' => $request['status'],
			'admin_id' => Admin::user()->id,
			'remark' => $request['remark']
		];

		if (isset($request['id'])) {
			$data['edit_time'] = time();
			$rs = DesignerTeam::update($data, [
				'id' => $request['id']
			]);
		} else {
			$data['add_time'] = time();
			$rs = DesignerTeam::create($data);
		}

		if ($rs) {
			if (isset($request['id'])) {
				$title = '修改成功';
			} else {
				$title = '添加成功';
			}

			$success = new MessageBag([
				'title' => $title
			]);
			return back()->with(compact('success'));
		} else {
			if (isset($request['id'])) {
				$title = '修改失败';
			} else {
				$title = '添加失败';
			}

			$error = new MessageBag([
				'title' => $title
			]);
			return back()->with(compact('error'));
		}
	}

	public function getAddressByAreaCode($area_code)
	{
		$address = '';
		if (!empty($area_code)) {
			$address = explode(',', $area_code);
			$province = Region::getNameByCode($address[0]);
			$city = Region::getNameByCode($address[1]);
			$area = Region::getNameByCode($address[2]);

			$address = $province . ' ' .$city . ' ' .$area;
		}

		return $address;
	}

	/**
	 * 根据图片url获取图片的大图
	 * @param $pic_url
	 * @param bool $is_thumbnail
	 * @return string
	 */
	public function getUrl($pic_url, $is_thumbnail = false)
	{
		$real_url = self::DEFAULT_PIC;

		if (!empty($pic_url)) {
			$split_str = explode('?', $pic_url);
			$temp = explode('/', $split_str[0]);
			$obj_id = end($temp);

			if ($is_thumbnail) {
				if (strpos($pic_url, ImgUrl::APPTYPE_BIZ) !== false) {
					$real_url = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $obj_id, ImgUrl::IMAGE_SIZE_SQ_THUMB);
				} elseif (strpos($pic_url, ImgUrl::APPTYPE_BAUTH) !== false) {
					$real_url = ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $obj_id, ImgUrl::IMAGE_SIZE_SQ_THUMB, self::AUTH_PIC_EXPIRE_TIME);
				} elseif (strpos($pic_url, ImgUrl::APPTYPE_OP) !== false) {
					$real_url = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $obj_id, ImgUrl::IMAGE_SIZE_SQ_THUMB);
				} else {
					$obj_id = $pic_url;
					$real_url = ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $obj_id, ImgUrl::IMAGE_SIZE_SQ_THUMB, self::AUTH_PIC_EXPIRE_TIME);
				}
			} else {
				if (strpos($pic_url, ImgUrl::APPTYPE_BIZ) !== false) {
					$real_url = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $obj_id, ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG);
				} elseif (strpos($pic_url, ImgUrl::APPTYPE_BAUTH) !== false) {
					$real_url = ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $obj_id, ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG, self::AUTH_PIC_EXPIRE_TIME);
				} elseif (strpos($pic_url, ImgUrl::APPTYPE_OP) !== false) {
					$real_url = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $obj_id, ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG);
				} else {
					$obj_id = $pic_url;
					$real_url = ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $obj_id, ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG, self::AUTH_PIC_EXPIRE_TIME);
				}
			}
		}

		return $real_url;
	}

	// 填写备注弹框页面
	public function remarkLayer($uid)
	{
		return view('DesignerAuth::audit.case_reject', [
			'uid' => $uid,
		]);
	}

	public function editRemark(Request $request, $tab_id, $id)
	{
		$pjax = true;
		$status = true;
		$id = $request->input('pk');
		$name = $request->input('name');
		$value = $request->input('value');

		$admin_name = Admin::user()->username;

		$auth_info = DesignerAuth::get('*', [
			'id' => $id
		]);

		$msg = implode("\n", [
			"操作：填写备注",
			"备注：{$value}",
			"设计师uid：{$auth_info['uid']}",
			"操作人：{$admin_name}\n",
		]);
        DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($auth_info['uid'], $msg);

		$message = '保存成功';
		try {
			if (isset($name) && isset($value)) {
				switch ($name) {
					case 'remark2':
						$pjax = false;
						if (mb_strlen($value) > 300) {
							throw new \Exception('最多300字');
						}
						DesignerAuth::update([
							'remark2' => $value
						], [
							'id' => $id
						]);
						break;
					default:
						throw new \Exception('未开发的功能');
						break;
				}
			}
		} catch (\Exception $e) {
			$status = false;
			$message = $e->getMessage();

			if (!$pjax) {
				return response()->json(['errors' => [$message]], 422);
			}
		}

		return response()->json(compact('message', 'status'));
	}

	public function exportData(Request $request)
	{

		$params = $request->all();

		$condition = [];
		if (isset($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (!empty($params['expire_time']['>='])) {
			$condition['expire_time[>=]'] = $params['expire_time']['>='];
		}

		if (!empty($params['expire_time']['<='])) {
			$condition['expire_time[<=]'] = $params['expire_time']['<='];
		}

		if (!empty($params['auth_time']['>='])) {
			$condition['auth_time[>=]'] = $params['auth_time']['>='];
		}

		if (!empty($params['auth_time']['<='])) {
			$condition['auth_time[<=]'] = $params['auth_time']['<='];
		}

		if (!empty($params['update_time']['>='])) {
			$condition['update_time[>=]'] = $params['update_time']['>='];
		}

		if (!empty($params['update_time']['<='])) {
			$condition['update_time[<=]'] = $params['update_time']['<='];
		}

		if (!empty($params['create_time']['>='])) {
			$condition['create_time[>=]'] = $params['create_time']['>='];
		}

		if (!empty($params['create_time']['<='])) {
			$condition['create_time[<=]'] = $params['create_time']['<='];
		}

		if (!empty($params['auth_time']['<='])) {
			$condition['auth_time[<=]'] = $params['auth_time']['<='];
		}

		if (isset($params['house_article_audit_status'])) {
			$condition['house_article_audit_status'] = $params['house_article_audit_status'];
		}

		if (isset($params['identity_info_audit_status'])) {
			$condition['identity_info_audit_status'] = $params['identity_info_audit_status'];
		}

		if (isset($params['auth_status'])) {
			$condition['auth_status'] = $params['auth_status'];
		}

		if (isset($params['designer_type'])) {
			$condition['designer_type'] = $params['designer_type'];
		}

		if (isset($params['is_test'])) {
			$condition['is_test'] = $params['is_test'];
		}

		$condition['ORDER'] = [
			'update_time' => 'DESC'
		];

        $total = DesignerAuth::count($condition);
        if (empty($total)) {
            $error = new MessageBag([
                'title' => '暂无数据可导出'
            ]);

            return back()->with(compact('error'));
        }
        if ($total > 5000) {
            $error = new MessageBag([
                'title' => '数据量太大请分批导出'
            ]);

            return back()->with(compact('error'));
        }

        $page_size = 1000;
        $page = ceil($total / $page_size);
        $data = [];
        for ($i = 1; $i <= $page; $i++) {
            $condition['LIMIT'] = [
                ($i - 1) * $page_size,
                $page_size
            ];

            $lists = DesignerAuth::select('*', $condition);
            $lists = is_array($lists) ? $lists : [];


            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);
            // 获取认证扩展字段
            $auth_extends = DesignerAuthExtend::select(['now_area', 'uid'], ['uid' => $user_ids]);
            $auth_extends_map = array_column($auth_extends, null, 'uid');
            unset($auth_extends);

            $sale_bind_info = AdmSaleBind::select('*', [
                'uid' => $user_ids,
                'data_status' => AdmSaleBind::STATUS_NORMAL
            ]);
            $map_sale = array_column($sale_bind_info, 'admin_name', 'uid');

            // 上一任销售
            $user_ids_str = implode(',', $user_ids);
            $log_id = AdmSaleBindLog::query("select max(id) id from `hhz_adm_sale_bind_log` where uid in ({$user_ids_str}) group by uid")->fetchAll();
            $designer_order_map = array();
            if ($log_id) {
                $designer_order = AdmSaleBindLog::select(['admin_name', 'uid'], ['id' => array_column($log_id, 'id')]);
                $designer_order_map = array_column($designer_order, 'admin_name', 'uid');
            }

            foreach ($lists as $item) {
                $create = date('Y-m-d', strtotime($item['create_time']));
                $update = date('Y-m-d', strtotime($item['update_time']));
                $address = $auth_extends_map[$item['uid']]['now_area'] ? explode(',', $auth_extends_map[$item['uid']]['now_area']) : [];
                $province = $address[0] ? Region::getNameByCode($address[0]) : '';
                $city = $address[1] ? Region::getNameByCode($address[1]) : '';
                // 上一任销售 当用户是已认证并且有销售则展示
                $sale_admin_name = '';
                if ($item['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && !empty($designer_order_map[$item['uid']])) {
                    $sale_admin_name = $designer_order_map[$item['uid']];
                }
                $row = [
                    'uid' => $item['uid'],
                    'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
                    'sale_bind' => empty($map_sale[$item['uid']]) ? '' : $map_sale[$item['uid']],
                    'is_first' => $create == $update ? '首次提交' : '提交更新资料',
                    'designer_type_text' => self::DESIGNER_TYPE_OPTIONS[$item['designer_type']],
                    'create_time' => $item['create_time'],
                    'house_article_audit_text' => self::STATUS_AUDIT[$item['house_article_audit_status']],
                    'update_time' => $item['update_time'],
                    'identity_info_audit_text' => self::STATUS_AUDIT[$item['identity_info_audit_status']],
                    'is_pay' => self::PAY_STATUS[$item['is_pay']],
//				'auth_time' => empty($item['auth_time']) ? '' : date('Y-m-d H:i:s', $item['auth_time']),
//				'expire_time' => empty($item['expire_time']) ? '' : date('Y-m-d H:i:s', $item['expire_time']),
                    'auth_status_text' => DesignerAuth::AUTH_STATUS_DESC[$item['auth_status']],
//				'remark' => $item['remark'],
                    //'remark2' => $item['remark2'],
                    'is_test' => self::IS_TEST[$item['is_test']],
//				'admin_name' => $item['admin_name'],
//				'operate_time' => empty($item['operate_time']) ? '' : date('Y-m-d H:i:s', $item['operate_time']),
                    'province' => $province,
                    'city' => $city == '市辖区' ? $province : $city,
                    'enterprise_name' => $item['enterprise_name'],
                    'sale_admin_name' => $sale_admin_name,

                ];
                $data[] = $row;
            }
        }

		// 设置列宽
		$letter = range('A', 'P');
		$header = [
			'UID', '昵称', '对接销售', '状态', '申请身份', '提交申请时间', '案例审核状态', '最近一次修改资料时间', '资料审核状态', '支付状态', '认证状态', '是否测试号', '所在省', '所在市', '企业名称', '上一任销售'
		]; // 去掉 认证时间、到期时间、补充说明、处理人、处理时间

		$excel = new DownExcel();
		$excel->setFileName('设计师认证表 - ' . date('YmdHis'));
		$excel->setSheetTitle('设计师认证表');

		// 设置列宽
		$width = [
			'A' => 12,
			'B' => 20,
			'C' => 15,
			'D' => 15,
			'E' => 15,
			'F' => 22,
			'G' => 15,
			'H' => 22,
			'I' => 15,
			'J' => 15,
			'K' => 15,
			'L' => 12,
            'M' => 12,
            'N' => 12,
            'O' => 22,
            'P' => 12
		];

		$excel->setWidth($width);
		$excel->setDefaultStyleAlignment();

		foreach ($header as $key => $value) {
			// 设置字体
			$excel->setFrontName($letter[$key]);
			// 设置加粗
			$excel->setFrontBold("$letter[$key]1");
			// 设置大小
			$excel->setFrontSize($letter[$key]);
		}

		$excel->create($data, $header);
	}

    private function exportCsv($file_name, $header, $data)
    {
        $output = fopen('php://output', 'w');
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$file_name.csv");
        fputcsv($output, $header);
        $index = 0;
        foreach ($data as $value) {
            fputcsv($output, array_values($value));
            if ($index == 1000) {
                $index = 0;
                ob_flush();
                flush();
            }
            $index++;
        }
        fclose($output);
        unset($data);
        ob_flush();
        flush();
        exit();
    }

	public function basicPage($data, $user_info)
	{
		$uid = $data['uid'];
		$house_article_audit_status = (int)$data['house_article_audit_status'];
		$identity_info_audit_status = (int)$data['identity_info_audit_status'];
		$old_other_work = $data['other_work'];
		$auth_status = (int)$data['auth_status'];

		$auth_info_data = DesignerAuditLog::getByCondition([
			'AND' => [
				'audit_type' => DesignerAuditLog::AUDIT_TYPE_INFORMATION,
				'uid' => $uid,
			],
			'ORDER' => ['add_time' => 'DESC'],
		]);

		if (!empty($auth_info_data)) {
			$new_data = json_decode($auth_info_data['new_data'], true);
			if (empty($new_data['extend_info'])) {
				$new_data['extend_info'] = [];
			} else {
				unset($new_data['extend_info']['create_time'], $new_data['extend_info']['update_time']);
			}
			$data = array_merge($new_data['auth_info'], $new_data['extend_info']);
		}

		$data['register_time'] = date('Y-m-d H:i:s', $user_info['addtime']);
		$data['nick'] = $user_info['nick'];
		$data['apply_time'] = date('Y-m-d H:i:s', strtotime($data['create_time']));
        if (cDesignerViolation::isInTagPool(sDesignerViolationRecord::getViolationCacheTag(sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW), $uid)) {
            $data['punish_txt'] = sDesignerViolationRecord::PUNISH_TYPE_TXT_LIST[sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW];
        }
        $authInfo = DesignerAuth::getByUId($uid);
        $data['expire_time'] = date('Y-m-d H:i:s', $authInfo ? $authInfo['expire_time'] : 0);

		// 实景作品信息
		$pic_list = DesignerAuthPhotos::get('pic_list', [
			'uid' => $uid
		]);
		$real_works = [];
		if (!empty($pic_list)) {
			$pic_list = json_decode($pic_list, true);
			foreach ($pic_list as $item) {
				$temp = [];
				if (!empty($item['list'])) {
					foreach ($item['list'] as $pic_id) {
						$temp[] = $this->getUrl($pic_id);
					}
				}

				$real_works[] = [
					'name' => $item['name'],
					'pic_list' => $temp,
				];
			}
		}
		$data['real_works'] = $real_works;

		//处理手机号信息
        $data['phone'] = EncryptPhone::getDecryptPhoneInfo($data['encrypt_phone_id'],UserExtendPhoneScene::DESIGNER_AUTH_PHONE);

		// 对接销售
		$sale_bind = AdmSaleBind::getInfoByUid($uid);
		$data['sale_bind'] = $sale_bind ? $sale_bind['admin_name'] : '';
		$operator_bind = DesignerOperatorBind::getInfoByUid($uid);
		$data['operator_bind'] = $operator_bind ? $operator_bind['admin_name'] : '';

		// 身份证、公函信息
		$data['front_card_pic'] = $this->getUrl($data['front_card_pic']);
		$data['front_card_pic_thumbnail'] = $this->getUrl($data['front_card_pic'], true);
		$data['reverse_card_pic'] = $this->getUrl($data['reverse_card_pic']);
		$data['reverse_card_pic_thumbnail'] = $this->getUrl($data['reverse_card_pic'], true);
		$data['hand_card_pic'] = $this->getUrl($data['hand_card_pic']);
		$data['hand_card_pic_thumbnail'] = $this->getUrl($data['hand_card_pic'], true);
		$data['business_license_pic'] = $this->getUrl($data['business_license_pic']);
		$data['business_license_pic_thumbnail'] = $this->getUrl($data['business_license_pic'], true);
		$data['missive'] = $this->getUrl($data['missive']);
		$data['missive_thumbnail'] = $this->getUrl($data['missive'], true);

		// 服务价格
		$designer_info = Designer::getInfo($uid);
		$data['service_price'] = empty($designer_info) ? '无' : $designer_info['min_price'] .' ~ '. $designer_info['max_price'];
		// 热图数量
		$last_photos = Photos::getHotPhotosByUid($uid);
		$data['hot_photo'] = empty($last_photos) ? 0 : count($last_photos);
		// 是否在黑名单
		$blacklist = BlackList::getByCondition([
			'uid' => $uid,
			'type' => BlackList::TYPE_DESIGNER,
			'data_status' => 1,
		]);
		$data['is_in_black'] = empty($blacklist) ? '否' : '是';
		if ((int)$data['major'] === 6) {// 所学专业
			$data['major'] = empty($data['other_major']) ? '' : $data['other_major'];
		} else {
			$data['major'] = empty(self::MAJOR[$data['major']]) ? '' : self::MAJOR[$data['major']];
		}
		$data['price_info'] = "半包（{$data['half_pack_price']}元/㎡） 全包（{$data['full_pack_price']}元/㎡） 全案（{$data['whole_case_price']}元/㎡）";
		// 从哪儿知道好好住APP，并下载使用的
		if (!empty($data['where_know'])) {
			if ((int)$data['where_know'] === 10) {
				$data['where_know'] = $data['other_where_know'];
			} else {
				$data['where_know'] = self::WHERE_KNOW[$data['where_know']];
			}
		}
		$data['is_crew'] = self::IS_CREW[$data['is_crew']];

		// 认证服务记录
		$services = DesignerPayService::select('*', ['uid' => $data['uid']]);
		$services = is_array($services) ? $services : [];
		$service_data = [];
		if (!empty($services)) {
			$uids = array_column($services, 'uid');
			$user_info = Member::getUsers($uids);
			foreach ($services as $item) {
				$service_data[] = [
					'id' => $item['id'],
					'dsn' => $item['dsn'],
					'uid' => $item['uid'],
					'nick' => empty($user_info[$item['uid']]) ? '' : $user_info[$item['uid']]['nick'],
					'package_id' => $item['package_id'],
					'package_name' => $item['package_name'],
					'start_time' => date('Y-m-d H:i:s', $item['start_time']),
					'end_time' => date('Y-m-d H:i:s', $item['end_time']),
					'service_type_text' => self::SERVICE_TYPE[$item['service_type']],
					'status_text' => self::SERVICE_STATUS_TEXT[$item['status']]
				];
			}
		}

		$data['auth_status'] = self::STATUS_AUTH[$auth_status];
		$data['designer_type_text'] = DesignerAuth::DESIGNER_TYPE[$data['designer_type']];
		$data['now_area'] = $this->getAddressByAreaCode($data['now_area']);
		$data['house_article_audit_status_text'] = self::STATUS_AUDIT[$house_article_audit_status];
		$data['identity_info_audit_status_text'] = self::STATUS_AUDIT[$identity_info_audit_status];
		$data['is_work_design'] = self::IS_WORK_DESIGN[$data['is_work_design']];
		$data['team_size'] = DesignerAuthExtend::TEAM_SIZE[$data['team_size']];
		$data['job'] = self::JOB[$data['job']];
		$data['education'] = self::EDUCATION[$data['education']];
		$data['private_job'] = self::PRIVATE_JOB[$data['private_job']];
		$data['is_employee'] = $data['is_employee'] == 0 ? '否' : '是';
		$data['service_scope'] = self::SERVICE_SCOPE[$data['service_scope']];

		// 擅长的设计方向
		if (!empty($data['good_at_direction'])) {
			$arr_good_at_direction = explode(',', trim($data['good_at_direction']));
			$str_data = '';

			foreach ($arr_good_at_direction as $item) {
				if ((int)$item === 13) {
					$direction = $data['other_good_at_direction'];
				} else {
					$direction = self::GOOD_AT_DIRECTION[$item];
				}

				$str_data = $str_data. '、' .$direction;
			}

			$data['good_at_direction'] = $str_data;
		}

		// 擅长的风格
		if (!empty($data['good_at_style'])) {
			$arr_good_at_style = explode(',', trim($data['good_at_style']));
			$str_data = '';

			foreach ($arr_good_at_style as $item) {
				if ((int)$item === 15) {
					$style = $data['other_good_at_style'];
				} else {
					$style = self::GOOD_AT_STYLE[$item];
				}

				$str_data = $str_data. '、' .$style;
			}

			$data['good_at_style'] = $str_data;
		}

		$auth_photo = DesignerAuthPhotos::getByUId($uid);
		$pic_list = empty($auth_photo['pic_list']) ? [] : json_decode($auth_photo['pic_list'], true);

		$real_works = [];
		if (!empty($pic_list)) {
			foreach ($pic_list as $key => $item) {
				$images = [];
				if (!empty($item['list'])) {
					foreach ($item['list'] as $pic_id) {
						if (!empty($pic_id)) {
							$images[] = [
								'big_image' => $this->getUrl($pic_id),
								'thumbnail' => $this->getUrl($pic_id, true),
							];
						}
					}
				}

				if (!empty($images)) {
                    $checkSame = sBusinessJudgeArticle::getSimilarStatus("{$auth_photo['id']}_{$key}", 1);
					$real_works[] = [
						'name' => $item['name'],
						'images' => $images,
                        'checkSame' => $checkSame,
					];
				}
			}
		}

		if (in_array($house_article_audit_status, [DesignerAuth::STATUS_AUDIT_WAIT, DesignerAuth::STATUS_AUDIT_FAIL])) {
			$house_article_info = DesignerAuditLog::getByCondition([
				'AND' => [
					'audit_type' => DesignerAuditLog::AUDIT_TYPE_CASE,
					'uid' => $uid,
				],
				'ORDER' => ['add_time' => 'DESC'],
			]);

			if (!empty($house_article_info)) {
				$new_data = json_decode($house_article_info['new_data'], true);
				$other_work = $new_data['other_work'];
			} else {
				$other_work = $old_other_work;
			}
		} else {
			$other_work = $old_other_work;
		}

		$other_works = [];
		if (!empty($other_work)) {
			$temp_other_work = json_decode($other_work, true);
			if (is_array($temp_other_work)) {
				$other_work = $temp_other_work;
			}

			foreach ($other_work as $item) {
				if (isset($item['url'])) {
					$other_works[] = trim($item['url']);
				} else {
					$other_works[] = $item;
				}
			}
		}

		// 机构认证的套餐
		if ($data['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
			$order = DesignerOrder::getNewestOrder($uid);
			$data['package_name'] = empty($order) ? '' : $order['package_name'];
			$equity = Designer\DesignerEquity::getByCondition([
				'uid' => $uid,
				'data_status' => Designer\DesignerEquity::STATUS_NORMAL
			]);
			$data['max_bind'] = empty($equity) ? 0 : (int)$equity['num'] + (int)$equity['adm_num'];
			$data['has_bind'] = DesignerTeam::count([
				'org_uid' => $uid,
				'status' => DesignerTeam::STATUS_NORMAL
			]);
			$ka = KaDesigner::getByCondition([
				'uid' => $uid,
				'data_status' => KaDesigner::STATUS_NORMAL,
				'end_time[>=]' => time()
			]);
			$data['ka'] = empty($ka) ?
				'未购买' : date('Y-m-d H:i:s', $ka['start_time']). ' - ' .date('Y-m-d H:i:s', $ka['end_time']);

			$data['repeat'] = false;
			if (!empty($data['enterprise_name'])) {
				$same = DesignerAuth::select('*', [
					'enterprise_name' => trim($data['enterprise_name']),
					'designer_type' => DesignerAuth::DESIGNER_TYPE_COMPANY,
					'uid[!]' => $uid
				]);

				if (!empty($same)) {
					$data['repeat'] = true;
					$member = Member::getUsers(array_column($same, 'uid'));

					$repeat_user = [];
					foreach ($same as $item) {
						$auth_status_text = self::STATUS_AUTH[$item['auth_status']];
						$nick = empty($member[$item['uid']]['nick']) ? '' : $member[$item['uid']]['nick'];
						$repeat_user[] = $item['uid']. " - {$nick} ($auth_status_text)";
					}
					$data['repeat_user'] = implode('、', $repeat_user);
				}
			}
		}

		$article_num = Article::count([
			'uid' => $uid,
			'status' => Article::$base_normal_visible_status
		]);

		return view('DesignerAuth::info.basic', [
			'data' => $data,
			'other_works' => $other_works,
			'real_works' => $real_works,
			'services' => $service_data,
			'article_num' => empty($article_num) ? 0 : (int)$article_num
		]);
	}

	public static function getHistoryNick($uid) {
        $history_nick = MemberHistoryNick::select('history_nick', ['uid' => $uid]);
        return implode('、', $history_nick);
    }

    public function cancelAuthPop()
    {
    	Admin::style("#swal2-title {display:inline !important;} #nick {color: #dd4b39}");
    	return <<<SCRIPT
	    // 取消认证
	    $('.cancel-auth').unbind('click').click(function() {
		    var uid = $(this).data('uid');
		    var nick = $(this).data('nick');
		    
		    layer.prompt({
			    title:'请输入取消认证的原因（如：客户主动要求取消认证、资质不符合平台要求、违反平台规则等）', 
			    formType: 2,
			    area: ['580px', '150px'],
		    }, function(reason, index){
			    swal({
                        title: '确认要将设计师<\span id="nick">' + nick+ '<\/span>取消认证吗？',
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "确认取消认证",
                        cancelButtonText: "取消",
                        preConfirm: function() {
                        
                        // 请求
					    $.post('cancel_auth/' + uid, {'uid':uid, reason: reason}, function (data) {
						    $.pjax.reload('#pjax-container');
						    if(data.code == 1) {
							    swal(data.msg, '', 'success');
						    } else {
							    swal(data.msg, '', 'error');
						    }
					    });
                        }
                    });
                    layer.close(index);
                });
            });
SCRIPT;
    }

	public function opRecord(Request $request)
	{
		$params = $request->all();
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [];

		if (!empty($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (!empty($params['op'])) {
			$condition['op'] = $params['op'];
		}

		if (!empty($params['op_time']['start'])) {
			$condition['op_time[>=]'] = $params['op_time']['start'];
		}

		if (!empty($params['op_time']['end'])) {
			$condition['op_time[<=]'] = $params['op_time']['end']. " 23:59:59";
		}

		$condition['ORDER'] = ['op_time' => 'DESC'];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = DesignerOpLog::select('*', $condition);

		$total = 0;
		$search_params = '';
		if (!empty($lists)) {
			unset($condition['LIMIT']);
			$search_params = http_build_query($condition);
			unset($condition['ORDER']);

			$total = DesignerOpLog::count($condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);
			foreach ($lists as &$item) {
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ?
					'' : $member_info[$item['uid']]['nick'];
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel, $search_params) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
				$grid->disableActions();

				// 添加导出按钮
				$grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
					$url = url('/admin/DesignerAuth/export/audit_log?'. $search_params);
					$button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出操作记录表</span></a>
                    </div>';
					$tool->append($button);
				});

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('uid', '按用户uid检索')->placeholder('请输入uid');
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('op', '操作')->select(DesignerOpLog::OP_DESC);
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('op_time', '操作时间')->date();
					});
					$filter->expand();
				});

				$grid->column('uid', 'uid')->width(100)->display(function () {
					return "<a href='/admin/DesignerAuth/detail/{$this->uid}' target='_blank'>$this->uid</a>";
				})->copyable();
				$grid->column('nick', '昵称')->width(200)->copyable();
				$grid->column('op', '操作')->display(function () {
					return DesignerOpLog::OP_DESC[$this->op];
				})->width(160);
				$grid->column('reason', '原因');
				$grid->column('op_time', '操作时间')->width(160);
				$grid->column('admin_name', '操作人')->width(150);
			}
		);
		return $gridList->render();
	}
}
